<template>
  <div class="create-post">
    <!-- 顶部导航栏 -->
    <div class="post-header">
      <button class="back-btn" @click="goBack">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M19 12H5M12 19l-7-7 7-7" />
        </svg>
        <span>返回</span>
      </button>
      <h1>发表新帖</h1>
      <button class="submit-btn-header" @click="submitPost" :disabled="!canSubmit">
        {{ isSubmitting ? '发布中...' : '发布' }}
      </button>
    </div>

    <div class="post-form">
      <!-- 分类选择 -->
      <div class="form-group category-group">
        <label>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M4 4h7l2 2h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2z" />
          </svg>
          选择分类
        </label>
        <select v-model="postData.category" :class="{ 'has-value': postData.category }">
          <option value="">请选择分类</option>
          <option v-for="category in filteredCategories" :key="category.id" :value="category.id">
            {{ category.name }}
          </option>
        </select>
      </div>

      <!-- 标题输入 -->
      <div class="form-group title-group">
        <label>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M4 7h16M4 12h16M4 17h10" />
          </svg>
          帖子标题
        </label>
        <input type="text" v-model="postData.title" placeholder="给你的帖子起个标题吧..." maxlength="100">
        <span class="char-count" :class="{ 'limit-warning': postData.title.length > 90 }">
          {{ postData.title.length }}/100
        </span>
      </div>

      <!-- 内容输入 -->
      <div class="form-group content-group">
        <label>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
            <path d="M14 2v6h6M16 13H8M16 17H8M10 9H8" />
          </svg>
          帖子内容
        </label>
        <textarea v-model="postData.content" placeholder="分享你的想法..." rows="10"></textarea>
      </div>

      <!-- 图片上传 -->
      <div class="form-group images-group">
        <label>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
            <circle cx="8.5" cy="8.5" r="1.5"></circle>
            <polyline points="21 15 16 10 5 21"></polyline>
          </svg>
          添加图片
          <span class="image-hint">（最多{{ maxImages }}张）</span>
        </label>

        <!-- 图片上传按钮 -->
        <div class="image-upload-container" v-if="uploadedImages.length < maxImages">
          <input type="file" ref="imageInput" accept="image/*" multiple @change="handleImageUpload"
            style="display: none">
          <button class="upload-btn" @click="$refs.imageInput.click()">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
              <circle cx="8.5" cy="8.5" r="1.5"></circle>
              <polyline points="21 15 16 10 5 21"></polyline>
            </svg>
            <span>点击上传图片</span>
          </button>
        </div>

        <!-- 图片预览区域 -->
        <div class="image-preview-container" v-if="uploadedImages.length > 0">
          <div class="image-count">{{ uploadedImages.length }}/{{ maxImages }}</div>
          <div class="image-grid">
            <div v-for="(image, index) in uploadedImages" :key="image.id" class="image-item">
              <img :src="image.url" alt="预览图片" class="preview-image">
              <button class="remove-image-btn" @click="removeImage(index)">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <line x1="18" y1="6" x2="6" y2="18"></line>
                  <line x1="6" y1="6" x2="18" y2="18"></line>
                </svg>
              </button>
            </div>

            <!-- 继续添加图片按钮 -->
            <button v-if="uploadedImages.length < maxImages" class="add-more-image-btn"
              @click="$refs.imageInput.click()">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <line x1="12" y1="5" x2="12" y2="19"></line>
                <line x1="5" y1="12" x2="19" y2="12"></line>
              </svg>
            </button>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { publishPost, getForumCategoryPage, uploadFile } from '@/api/forum'

const router = useRouter()
const userStore = useUserStore()

const postData = ref({
  category: '',
  title: '',
  content: ''
})

const categories = ref([])
const isSubmitting = ref(false)

// 根据用户角色过滤分类
const filteredCategories = computed(() => {
  // 如果是超级管理员，显示所有分类
  if (userStore.isSuperAdmin) {
    return categories.value
  }
  // 普通用户过滤掉"官方公告"
  return categories.value.filter(cat => cat.name !== '官方公告')
})

// 图片上传相关变量
const uploadedImages = ref([]) // 存储图片URL
const maxImages = 6

const canSubmit = computed(() => {
  return postData.value.category &&
    postData.value.title.trim() &&
    postData.value.content.trim() &&
    !isSubmitting.value
})

const goBack = () => {
  router.back()
}

// 图片上传相关方法
const handleImageUpload = async (event) => {
  const files = Array.from(event.target.files)

  // 检查是否超过最大数量限制
  if (uploadedImages.value.length + files.length > maxImages) {
    alert(`最多只能上传${maxImages}张图片`)
    return
  }

  // 处理每个文件并上传
  for (const file of files) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('只能上传图片文件')
      continue
    }

    // 检查文件大小（限制为5MB）
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过5MB')
      continue
    }

    try {
      // 上传图片并获取URL
      const res = await uploadFile(file)
      if (res.code === 200 && res.msg) { // 修改判断条件，使用code===200并检查msg不为空
        const imageUrl = res.msg
        uploadedImages.value.push({
          url: imageUrl, // 使用msg字段作为URL
          id: Date.now() + Math.random()
        })
      } else {
        alert('图片上传失败')
      }
    } catch (error) {
      console.error('图片上传错误:', error)
      alert('图片上传失败')
    }
  }

  // 清空input值，允许重复选择同一文件
  event.target.value = ''
}

const removeImage = (index) => {
  uploadedImages.value.splice(index, 1)
}

// 重置表单
const resetForm = () => {
  postData.value = {
    category: '',
    title: '',
    content: ''
  }
  uploadedImages.value = []
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    const res = await getForumCategoryPage()
    if (res.code === 200 && res.data && res.data.list) {
      // 将API返回的数据转换为前端需要的格式
      categories.value = res.data.list.map(item => ({
        id: item.id.toString(),
        name: item.categoryName
      }))
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 组件挂载时获取分类数据
onMounted(async () => {
  // 如果用户已登录但没有角色信息，尝试获取
  if (userStore.uid && (!userStore.userRoles || userStore.userRoles.length === 0)) {
    try {
      const { getCurrentUserPermissions } = await import('@/api/user')
      const permissionRes = await getCurrentUserPermissions(userStore.uid)
      
      if (permissionRes.code === 200 && permissionRes.data && permissionRes.data.roleList) {
        userStore.setUserRoles(permissionRes.data.roleList)
      }
    } catch (error) {
      console.error('获取用户权限失败:', error)
    }
  }
  
  await fetchCategories()
})

const submitPost = async () => {
  if (!canSubmit.value) return

  // 检查用户是否已登录
  if (!userStore.uid) {
    alert('请先登录后再发布帖子')
    router.push('/user/login')
    return
  }

  isSubmitting.value = true

  try {
    // 构建帖子数据
    const submitData = {
      categoryId: postData.value.category,
      title: postData.value.title,
      content: postData.value.content,
      userId: userStore.uid,
      images: uploadedImages.value.map(img => img.url).join(',') // 将图片URL数组转换为逗号分隔的字符串
    }

    // 调用API发布帖子
    const res = await publishPost(submitData)

    if (res.code === 200) {
      alert('帖子发布成功！')
      // 重置表单
      resetForm()
      router.push('/forum')
    } else {
      alert('发布失败：' + (res.message || '未知错误'))
    }
  } catch (error) {
    console.error('发布帖子失败:', error)
    alert('发布失败，请检查网络连接后重试')
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.create-post {
  min-height: 100vh;
  background: linear-gradient(to bottom, #f8f9fa 0%, #ffffff 100%);
  padding-bottom: 20px;
}

/* 顶部导航栏 */
.post-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #ffffff;
  border-bottom: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.post-header h1 {
  flex: 1;
  text-align: center;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.back-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 8px 12px;
  background: transparent;
  border: none;
  border-radius: 8px;
  color: #333;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.back-btn svg {
  display: block;
}

.back-btn span {
  font-weight: 500;
}

.back-btn:active {
  background: #f0f0f0;
  transform: scale(0.95);
}

.submit-btn-header {
  padding: 8px 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.submit-btn-header:active {
  transform: scale(0.95);
}

.submit-btn-header:disabled {
  background: #d0d0d0;
  box-shadow: none;
  cursor: not-allowed;
}

/* 表单容器 */
.post-form {
  padding: 16px;
}

.form-group {
  background: white;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s;
}

.form-group:focus-within {
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);
  transform: translateY(-2px);
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.form-group label svg {
  color: #667eea;
}

.image-hint {
  font-size: 12px;
  font-weight: 400;
  color: #999;
  margin-left: 4px;
}

/* 分类选择 */
.category-group select {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  font-size: 15px;
  color: #666;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg width='12' height='8' viewBox='0 0 12 8' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1L6 6L11 1' stroke='%23666' stroke-width='2' stroke-linecap='round'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 16px center;
  padding-right: 40px;
}

.category-group select.has-value {
  color: #333;
  background-color: #f8f4ff;
  border-color: #667eea;
}

.category-group select:focus {
  outline: none;
  border-color: #667eea;
  background-color: white;
}

/* 标题输入 */
.title-group {
  position: relative;
}

.title-group input {
  width: 100%;
  padding: 12px 16px;
  padding-right: 60px;
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  font-size: 16px;
  color: #333;
  background: #fafafa;
  transition: all 0.3s;
  box-sizing: border-box;
}

.title-group input:focus {
  outline: none;
  border-color: #667eea;
  background-color: white;
}

.title-group input::placeholder {
  color: #bbb;
}

.char-count {
  position: absolute;
  right: 16px;
  bottom: 16px;
  font-size: 12px;
  color: #999;
  background: white;
  padding: 2px 6px;
  border-radius: 8px;
}

.char-count.limit-warning {
  color: #ff6b6b;
  font-weight: 600;
}

/* 内容输入 */
.content-group textarea {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  background: #fafafa;
  resize: vertical;
  min-height: 200px;
  transition: all 0.3s;
  box-sizing: border-box;
  font-family: inherit;
}

.content-group textarea:focus {
  outline: none;
  border-color: #667eea;
  background-color: white;
}

.content-group textarea::placeholder {
  color: #bbb;
}

/* 图片上传样式 */
.image-upload-container {
  margin-top: 12px;
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 20px;
  border: 2px dashed #ddd;
  border-radius: 12px;
  background: #fafafa;
  color: #999;
  cursor: pointer;
  transition: all 0.3s;
  gap: 8px;
}

.upload-btn:hover {
  border-color: #667eea;
  background: #f8f4ff;
  color: #667eea;
}

.upload-btn svg {
  width: 24px;
  height: 24px;
}

.upload-btn span {
  font-size: 14px;
  font-weight: 500;
}

.image-preview-container {
  margin-top: 12px;
}

.image-count {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
  text-align: right;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 10px;
}

.image-item {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f5f5;
}

.preview-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  border: none;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.remove-image-btn:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: scale(1.1);
}

.add-more-image-btn {
  width: 100%;
  height: 100%;
  border: 2px dashed #ddd;
  border-radius: 8px;
  background: #fafafa;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.add-more-image-btn:hover {
  border-color: #667eea;
  background: #f8f4ff;
  color: #667eea;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .create-post {
    background: #f8f9fa;
  }

  .post-form {
    padding: 12px;
  }

  .form-group {
    border-radius: 12px;
    padding: 14px;
  }

  .title-group input,
  .content-group textarea,
  .category-group select {
    font-size: 16px;
    /* 防止iOS自动缩放 */
  }
}

/* 触摸反馈优化 */
@media (hover: none) {
  .back-btn:hover {
    background: transparent;
  }
}
</style>